package com.fast.fast.common.gateway.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fast.fast.common.base.constant.CacheConstants;
import com.fast.fast.common.gateway.entity.SysRole;
import com.fast.fast.common.gateway.entity.SysUserRole;
import com.fast.fast.common.gateway.mapper.SysRoleMapper;
import com.fast.fast.common.gateway.service.SysRoleService;
import com.fast.fast.common.gateway.service.SysUserRoleService;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author lyf
 * @description 针对表【sys_role(系统角色表)】的数据库操作Service实现
 * @createDate 2022/01/01 00:00 周六
 */
@RequiredArgsConstructor
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole>
        implements SysRoleService {

    private final SysUserRoleService sysUserRoleService;

    @Cacheable(cacheNames = CacheConstants.GATEWAY_LOGIN_SYS_ROLE_CODE_USERID)
    @Override
    public List<String> listRoleCodesByUserId(Long userId) {
        if (ObjectUtil.isEmpty(userId)) {
            return CollUtil.newArrayList();
        }

        // 根据userId,获取roleIds
        List<Long> roleIds = sysUserRoleService.list(
                Wrappers.lambdaQuery(SysUserRole.class)
                        .eq(SysUserRole::getUserId, userId)
        ).stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
        if (ObjectUtil.isEmpty(roleIds)) {
            return CollUtil.newArrayList();
        }

        // 根据roleIds,获取roleCodes
        List<String> roleCodes = list(
                Wrappers.lambdaQuery(SysRole.class)
                        .in(CollUtil.isNotEmpty(roleIds), SysRole::getId, roleIds)
        ).stream().map(SysRole::getCode).filter(Objects::nonNull).collect(Collectors.toList());

        return roleCodes;
    }
}




